//
//  DataEngine.m
//  Nurse
//
//  Created by 夏 申频 on 14-1-5.
//  Copyright (c) 2014年 Honeywell. All rights reserved.
//

#import "DataEngine.h"
#import "ASIHTTPRequest.h"


#if TARGET_IPHONE_SIMULATOR
#define DEFAULTSERVER        @"javaee.oritsh.com"    // 模拟器
#elif TARGET_OS_IPHONE
#define DEFAULTSERVER        @"javaee.oritsh.com"       // 真机
#endif

NSString* const DEFAULTHostname = DEFAULTSERVER;
NSString* const DEFAULTAppname = @"echart";

typedef enum {
    XDefultFailed = -1000,
    XRegisterFailed,
    XConnectFailed,
    XNotBindedFailed
}CustomErrorFailed;

@interface DataEngine()
@property (copy,nonatomic) NSString* hostname;
@property (copy,nonatomic) NSString* appName;
@property (strong,nonatomic) UIAlertView* waitView;
@property (strong,nonatomic) NSOperationQueue* requestQueue;
-(ASIHTTPRequest*) prepareRequest:(ASIHTTPRequest*)request forData:(NSData*)data andMethod:(NSString*) method;

@end

@implementation DataEngine

+(DataEngine*) sharedInstance{
    static dispatch_once_t pred = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[DataEngine alloc] initWithHostName:nil];
        [_sharedObject setAppName:DEFAULTAppname];
    });
    return _sharedObject;
}
-(DataEngine*) initWithHostName:(NSString*) hostname{
    self = [super init];
    if (self) {
        if (hostname ==nil) {
            hostname = DEFAULTHostname;
            NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
            NSString* hisServer = [defaults objectForKey:@"HIS_Server"];
            if ([hisServer isEqual:@"ServerDemo"]) {
                hostname=@"javaee.oritsh.com";
            }
            else if ([hisServer isEqual:@"ServerA"]) {
                hostname=@"192.10.6.80:8080";
            }
            else if ([hisServer isEqual:@"ServerB"]) {
                hostname=@"10.120.1.7:8080";
            }
        }
        [self setHostname:hostname];
        self.requestQueue = [[NSOperationQueue alloc]init];
        self.requestQueue.maxConcurrentOperationCount =10;
        
    }
    return self;
    
}

-(void)showMessage:(NSString*)message withTitle:(NSString*)title{
    if (title == nil) {
        title = self.appName;
    }
    UIAlertView* alterView = [[UIAlertView alloc] initWithTitle:title
                               message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alterView show];
}

-(NSURL*) urlForPath:(NSString*)path{
    NSString* s = [NSString stringWithFormat:@"http://%@/%@/%@",self.hostname,self.appName,path];
    return [NSURL URLWithString:s];
}


-(void)postRequest:(NSData*)data forPath:(NSURL*)url withHandle:(RawHandler)handler{
    
    ASIHTTPRequest *httpRequest = [ASIHTTPRequest requestWithURL:url];
    
    __weak ASIHTTPRequest* request= [self prepareRequest:httpRequest forData:data andMethod:@"POST"];
    
    
    [request setCompletionBlock:^{
        NSData *responseData = [request responseData];
        handler(responseData,nil);
        
    }];
    
    //__weak DataEngine* this = self;
    
    [request setFailedBlock:^{
        
        NSError *error = [request error];
        //NSString* description = [error description];
        //[this showMessage:description withTitle:@"访问服务器时出错"];
        handler(nil,error);
        
    }];
    if(request!=nil)
        // [r startAsynchronous];
        [self.requestQueue addOperation:request];
    NSLog(@"Request url:%@",request.url);
}

-(void)postJsonRequest:(id)obj forPath:(NSURL*)url withSuccessHandler:(SuccessHandler)successHandler andFailHandler:(FailHandler)failHandler{
    NSError *jsonError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj
                                                       options:NSJSONWritingPrettyPrinted error:&jsonError];
    
    if (failHandler == nil) {
        __weak DataEngine* this = self;
        failHandler = ^(NSError* error,NSString* title){
            if (title == nil) {
                title = this.appName;
            }
            [this showMessage:[error description] withTitle:title];
        };
    }
    
    if (jsonError) {
        NSString* msg = [NSString stringWithFormat:@"jsonRequest:error:%@.can't convert %@ to json data!",jsonError,obj];
        NSLog(@"%@",msg);
        failHandler(jsonError,@"将数据序列化为JSON时出错");
    }else{
        //__weak DataEngine* this = self;
        [self postRequest:jsonData forPath:url withHandle:^(NSData* data,NSError* error){
            if (error!=nil) {
                failHandler(error,@"执行服务器访问时网络出现错误");
            }else if(data != nil){
                NSError *jsonError = nil;
                id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
                if(jsonError == nil){
                    if (successHandler != nil) {
                        successHandler(jsonObject);
                    }
                }else{
                    failHandler(jsonError,@"将返回结果转换为JSON时出错");
                }
            }
        }];
    }
}

-(void)callProcedure:(ProcedureCallRequest*)procedureRequest forURL:(NSURL*)url{
    NSMutableDictionary* postData = [NSMutableDictionary dictionary];
    [postData setValue:procedureRequest.procedureName forKey:@"procedure"];
    [postData setValue:procedureRequest.params forKey:@"params"];
    
    [self postJsonRequest:postData forPath:url
     withSuccessHandler:^(id obj){
         id result = [procedureRequest parsePRODUCEResponse:obj];
         if ([result isKindOfClass:[NSError class]]) {
             if (procedureRequest.failHandle != nil) {
                 procedureRequest.failHandle(result,@"处理返回数据时出错");
             }
         }else {
             if (procedureRequest.successHandle != nil) {
                 procedureRequest.successHandle(result);
             }
             
         }
    }
     andFailHandler:procedureRequest.failHandle];
}

+(NSError*)makeErrorForMsg:(NSString*)errMsg{
    NSString* CustomErrorDomain = @"com.oritsh.nurse";
    
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errMsg                                                                      forKey:NSLocalizedDescriptionKey];
    
    NSError *aError = [NSError errorWithDomain:CustomErrorDomain code:XDefultFailed userInfo:userInfo];
    
    return aError;
}

-(ASIHTTPRequest*) prepareRequest:(ASIHTTPRequest*)request forData:(NSData*)data andMethod:(NSString*) method{
    NSMutableDictionary *headerFields = [NSMutableDictionary dictionary];
    [headerFields setValue:@"application/json" forKey:@"Content-Type"];
    [headerFields setValue:@"application/json;charset=UTF-8" forKey:@"Accept"];
    [headerFields setValue:@"UTF-8" forKey:@"Accept-Charset"];
    [headerFields setValue:@"iOS" forKey:@"x-client-identifier"];
    [request setResponseEncoding:NSUTF8StringEncoding];
    [request setRequestMethod:method];
    [request setRequestHeaders:headerFields];
    [request setTimeOutSeconds:60];
    [request appendPostData:data];
    return request;
}

@end
